package us.icitap.commandcenter.ui.operator;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import us.icitap.commandcenter.CommandCenterUI;
import us.icitap.commandcenter.business.CallActionEnum;
import us.icitap.commandcenter.business.ejb.persistence.Call;
import us.icitap.commandcenter.business.ejb.persistence.CallReason;
import us.icitap.commandcenter.business.ejb.persistence.CallStatusEnum;
import us.icitap.commandcenter.business.ejb.persistence.Dispatcher;
import us.icitap.commandcenter.business.ejb.persistence.Grade;
import us.icitap.commandcenter.listeners.OperatorListener;
import us.icitap.commandcenter.ui.custom.ButtonsLayout;
import us.icitap.commandcenter.ui.custom.ConfirmDialogAction;
import us.icitap.commandcenter.ui.custom.CustBeanFieldGroup;
import us.icitap.commandcenter.ui.custom.CustButton;
import us.icitap.commandcenter.ui.custom.CustComboBox;
import us.icitap.commandcenter.ui.custom.CustConfirmDialog;
import us.icitap.commandcenter.ui.custom.CustSaveButton;
import us.icitap.commandcenter.ui.custom.CustTextArea;
import us.icitap.commandcenter.ui.custom.CustTextField;
import us.icitap.commandcenter.ui.custom.CustVerticalLayout;
import us.icitap.commandcenter.utils.HandleNotification;
import us.icitap.commandcenter.utils.ProjectLists;

import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.fieldgroup.BeanFieldGroup;
import com.vaadin.data.fieldgroup.FieldGroup.CommitException;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.ui.AbstractSelect.ItemCaptionMode;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.Field;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.Runo;

public class CallForm extends CustVerticalLayout implements ClickListener{


	CallActionEnum callActionEnum;
	
	private Call call;
	private Call baseCall;
	
	private final CustBeanFieldGroup<Call> binder = new CustBeanFieldGroup<Call>(Call.class);
	

	private  final CustTextField callerTextField = new CustTextField("Telefonuesi");
	private  final CustTextArea addressTextArea = new CustTextArea("Adresa");
	private  final CheckBox anonimCheckBox = new CheckBox("Telefonate anonime");
	private  final CustComboBox dispatcherComboBox = new CustComboBox("Zona e mbulimit");
	private  final CustComboBox callReasonComboBox = new CustComboBox("Arsyeja e telefonates");
	private final CustTextArea descTextArea = new CustTextArea("Pershkrimi");
	private final CustComboBox gradeComboBox = new CustComboBox("Grada e telefonates");
	private final CheckBox forSupervisorCheckBox = new CheckBox("Telefonate per supervizorin");
	private final CheckBox officerCallCheckBox = new CheckBox("Telefonate nga punonjes policie");
	
	private final  CustSaveButton saveButton = new CustSaveButton("RUAJ");
	private final  CustButton resetButton = new CustButton("Pastro");
	
	
	private final OperatorListener operatorListener;
	

	private final VerticalLayout vlHeader = new VerticalLayout();
	private final Label labelHeader = new Label("TELEFONATE E RE", ContentMode.HTML);
	
	
	public CallForm(OperatorListener operatorListener, List<Dispatcher> dispatcherList) {
		
		this.setCaption("Rregjistrimi i telefonatave");
		labelHeader.setSizeUndefined();
		vlHeader.addComponent(labelHeader);
		vlHeader.setComponentAlignment(labelHeader, Alignment.MIDDLE_CENTER);
		vlHeader.addStyleName("callFormHeader");
		
		this.addComponent(vlHeader);
		this.operatorListener = operatorListener;
		
		resetForm();
		binder.setItemDataSource(call);
		
		binder.bind(anonimCheckBox, "anonymousCaller");
		binder.bind(callerTextField, "caller");
		binder.bind(callReasonComboBox, "callReason");
		binder.bind(descTextArea, "description");
		binder.bind(addressTextArea, "address");
		binder.bind(dispatcherComboBox, "mainDispatcher");
//		binder.bind(gradeComboBox, "actualGrade");
		binder.bind(forSupervisorCheckBox, "forSupervisor");
		binder.bind(officerCallCheckBox, "officerCall");
		
		
		List<CallReason> callReasonList =  ProjectLists.getCallReasonList(false);
		
		callReasonComboBox.setContainerDataSource(new BeanItemContainer<CallReason>(CallReason.class, callReasonList));
		callReasonComboBox.setItemCaptionMode(ItemCaptionMode.EXPLICIT);
		callReasonComboBox.setItemCaptionPropertyId("tag");
		
		List<Dispatcher> dispatchers;
		
		if(dispatcherList == null || dispatcherList.isEmpty())
			dispatchers = CommandCenterUI.getUser().getCommandCenter().getActiveDispatcherList();	
		else
			dispatchers = dispatcherList;
		
		dispatcherComboBox.setContainerDataSource(new BeanItemContainer<Dispatcher>(Dispatcher.class, dispatchers));
		dispatcherComboBox.setItemCaptionMode(ItemCaptionMode.EXPLICIT);
		dispatcherComboBox.setItemCaptionPropertyId("name");
		dispatcherComboBox.setImmediate(true);
		if(dispatchers.size() == 1){
			dispatcherComboBox.setValue(dispatchers.get(0));
		}
		
		
		List<Grade> gradeList = ProjectLists.getGradeList();
		gradeComboBox.setContainerDataSource(new BeanItemContainer<Grade>(Grade.class, gradeList));
		gradeComboBox.setItemCaptionMode(ItemCaptionMode.EXPLICIT);
		gradeComboBox.setItemCaptionPropertyId("tag");
		
		anonimCheckBox.setImmediate(true);
		callerTextField.setImmediate(true);
		officerCallCheckBox.setImmediate(true);
		callReasonComboBox.setImmediate(true);
		
		anonimCheckBox.addValueChangeListener(new ValueChangeListener() {
			
			@Override
			public void valueChange(ValueChangeEvent event) {
				if(anonimCheckBox.getValue().booleanValue()){
					callerTextField.setValue(null);
					callerTextField.setEnabled(false);
				}
				else
					callerTextField.setEnabled(true);
				
			}
		});
		
		officerCallCheckBox.addValueChangeListener(new ValueChangeListener() {
			
			@Override
			public void valueChange(ValueChangeEvent event) {
				if(officerCallCheckBox.getValue().booleanValue()){
					anonimCheckBox.setValue(new Boolean(false));
					callerTextField.setEnabled(true);
				}
				
				
			}
		});
			
		final FormLayout formLayout = new FormLayout();
		
		formLayout.addComponent(anonimCheckBox);
		formLayout.addComponent(callerTextField);
		formLayout.addComponent(officerCallCheckBox);
		formLayout.addComponent(addressTextArea);
		formLayout.addComponent(descTextArea);
		formLayout.addComponent(callReasonComboBox);
		formLayout.addComponent(dispatcherComboBox);
		formLayout.addComponent(forSupervisorCheckBox);
		
//		formLayout.addComponent(gradeComboBox);
		
		this.addComponent(formLayout);
		
		
		final ButtonsLayout buttonsLayout = new ButtonsLayout("500px");
		
		buttonsLayout.addComponent(resetButton);
		buttonsLayout.addComponent(saveButton);
		buttonsLayout.setComponentAlignment(saveButton, Alignment.MIDDLE_RIGHT);
		this.addComponent(buttonsLayout);
		
		
		
		resetButton.addStyleName(Runo.BUTTON_LINK);
		this.resetButton.addStyleName("resetButton");
		this.addressTextArea.setWidth("300px");
		this.descTextArea.setWidth("300px");
		
		this.addStyleName("borders");
		this.setSizeUndefined();
		this.setMargin(true);
		
		this.saveButton.addClickListener(this);
		this.resetButton.addClickListener(this);
		
	}



	@Override
	public void buttonClick(ClickEvent event) {
		
		if(event.getComponent() == saveButton)
			CustConfirmDialog.show(this.getConfirmDialogAction(), this.getUI(), "Doni te ruani telefonaten?");
		else if(event.getComponent() == resetButton){
			this.resetForm();
		}
			
	}


	public void resetForm(){
		setComponentsEnable(true);
		dispatcherComboBox.setEnabled(true);
		callActionEnum = CallActionEnum.NEW_CALL;
		call = new Call(CommandCenterUI.getUser().getUsername());
		binder.setItemDataSource(call);	
		labelHeader.setValue("TELEFONATE E RE");
	}
	
	private void setComponentsEnable(boolean enable){
		this.callerTextField.setEnabled(enable);
		this.addressTextArea.setEnabled(enable);
		this.descTextArea.setEnabled(enable);
		this.anonimCheckBox.setEnabled(enable);
		this.callReasonComboBox.setEnabled(enable);
		this.forSupervisorCheckBox.setEnabled(enable);
		this.officerCallCheckBox.setEnabled(enable);
		this.dispatcherComboBox.setEnabled(enable);
	}
	public void resetForm(Call call, CallActionEnum callActionEnum){
		
		this.callActionEnum = callActionEnum;
		
		if(callActionEnum.equals(CallActionEnum.NEW_CALL_RELATED)){
			this.call = new Call(CommandCenterUI.getUser().getUsername());
			this.baseCall = call;
			this.copyCallData(baseCall);
			labelHeader.setValue("TELEFONATE TJETER E LIDHUR ME NJE TELEFONATE TE MEPARSHME");
		}
		else if(callActionEnum.equals(CallActionEnum.UPDATE_CALL)){
			this.call = call;	
			labelHeader.setValue("KORIGJIM I TE DHENAVE");
		}
		else if(callActionEnum.equals(CallActionEnum.CHANGE_DISPATCHER)){
			this.call = call;	
			labelHeader.setValue("NDRYSHIMI I ZONES SE MBULIMIT");
		}

		binder.setItemDataSource(this.call);		
		 if(callActionEnum.equals(CallActionEnum.CHANGE_DISPATCHER)){
			 this.setComponentsEnable(false);
			 this.dispatcherComboBox.setEnabled(true);
		 }
		 else
			 this.setComponentsEnable(true);
		 if(CallActionEnum.UPDATE_CALL.equals(callActionEnum) || CallActionEnum.NEW_CALL_RELATED.equals(callActionEnum))
			 this.dispatcherComboBox.setEnabled(false);
		
	}
	
	private void copyCallData(Call prevoiusCall){
		call.setCommandCenter(prevoiusCall.getCommandCenter());
		call.setCaller(prevoiusCall.getCaller());
		call.setAnonymousCaller(prevoiusCall.isAnonymousCaller());
		call.setDescription(prevoiusCall.getDescription());
		call.setAddress(prevoiusCall.getAddress());
		call.setCallReason(prevoiusCall.getCallReason());
		call.setMainDispatcher(prevoiusCall.getMainDispatcher());
		call.setActualGrade(prevoiusCall.getActualGrade());
		call.setActualStatus(prevoiusCall.getActualStatus());
		call.setRecordUser(CommandCenterUI.getUser().getUsername());
		
	}
	private ConfirmDialogAction getConfirmDialogAction(){
		ConfirmDialogAction confirm = new ConfirmDialogAction() {
			
			@Override
			public void actYes() {
				try {
					
					Dispatcher d = call.getMainDispatcher();
					
							
					binder.commit();		
					if(CallActionEnum.NEW_CALL.equals(callActionEnum)){
						call.setCommandCenter(CommandCenterUI.getUser().getCommandCenter());
						call.setActualStatus(CallStatusEnum.N);	
						operatorListener.addNewCall(call);
					}
					else if(CallActionEnum.NEW_CALL_RELATED.equals(callActionEnum)){
						call.setBaseCall(baseCall);
						call.setCommandCenter(CommandCenterUI.getUser().getCommandCenter());
						call.setRecordDate(new Date());
						if(baseCall.getRelatedCallList() == null)
							baseCall.setRelatedCallList(new ArrayList<Call>());
						baseCall.getRelatedCallList().add(call);
						operatorListener.addNewCallRelated(baseCall);
					}
					else if (CallActionEnum.UPDATE_CALL.equals(callActionEnum)){
						operatorListener.updateCallInformation(call);
					}
					else if(CallActionEnum.CHANGE_DISPATCHER.equals(callActionEnum)){
						call.setPreviousDispatcher(d);
						for (Call c : call.getRelatedCallList()) {
							c.setPreviousDispatcher(d);
							c.setMainDispatcher(call.getMainDispatcher());
						}
						operatorListener.changeDispatcher(call);
					}

				} catch (CommitException e) {
					HandleNotification.showWarningOnScreen(e.getCause().getMessage());
				}
				
			}
			
			@Override
			public void actNO() {
				
				
			}
		};
		
		return confirm;
	}
	
	
}
